package com.ailot.cloud.upms.api.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ailot.cloud.base.common.constants.SecurityConstant;
import com.ailot.cloud.base.common.exception.BizException;
import com.ailot.cloud.base.security.model.JwtUser;
import com.ailot.cloud.upms.api.service.JwtUserDetailsService;
import com.ailot.cloud.upms.api.service.SysUserService;
import com.ailot.cloud.upms.common.dto.JwtUserDTO;
import com.ailot.cloud.upms.common.entity.SysUser;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

@Service
@AllArgsConstructor
public class JwtUserDetailsServiceImpl implements JwtUserDetailsService {

    private final SysUserService sysUserService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
        if (ObjectUtil.isEmpty(sysUser)) {
            throw new BizException(String.format("用户信息为空 %s", username));
        }
        JwtUserDTO jwtUserDTO = sysUserService.getUserDetail(sysUser);
        UserDetails userDetails = AssembleUserDetails(jwtUserDTO);
        return userDetails;
    }

    /**
     * 组装userDetails
     *
     * @return
     */
    private UserDetails AssembleUserDetails(JwtUserDTO jwtUserDTO) {
        SysUser sysUser = jwtUserDTO.getSysUser();
        Set<String> authsSet = new HashSet<>();
        if (ArrayUtil.isNotEmpty(jwtUserDTO.getRoles())) {
            Arrays.asList(jwtUserDTO.getRoles()).forEach(id -> authsSet.add(SecurityConstant.ROLE + id));
            authsSet.addAll(Arrays.asList(jwtUserDTO.getPermissions()));
        }
        Collection<? extends GrantedAuthority> authorities
                = AuthorityUtils.createAuthorityList(authsSet.toArray(new String[0]));
        return new JwtUser(sysUser.getId(), sysUser.getOrgId(), sysUser.getUsername(), sysUser.getPassword(), authorities);
    }

    @Override
    public UserDetails loadUserByPhone(String code) throws UsernameNotFoundException {
        return null;
    }
}
